import { HTTP } from '../utils/http'
import { default as ProductUtils } from '../utils/product'
import { User as UserUtils } from '../utils/user'

const productUtils = new ProductUtils()
const userUtils = new UserUtils()

class CollectionService extends HTTP {

    /**
     * 新增一个订单对象
     * @param {any} product 产品对象
     */
    addCollection(product: any): Promise<any> {
        const userInfo = userUtils.getUserFromLocalStorage()
        const { token } = userInfo

        if (userUtils.isLoginValid()) {
            const { product_id } = product
            const loan_type = productUtils.getProductLoanType(product)

            const param = {
                product_id,
                loan_type,
            }

            return this.request({
                url: '/mini/collection',
                method: 'POST',
                data: param,
                header: {
                    Authorization: userUtils.getBearToken(token),
                }
            })
        }

        const empty = new Promise((resolve, reject) => {
            resolve({})
        })
        return empty
    }

    /**
     * 根据收藏产品id批量删除当前用户的收藏
     * @param {Array} collection_ids 收藏id数组
     */
    removeCollection(collection_ids: string[]): Promise<any> {
        const userInfo = userUtils.getUserFromLocalStorage()
        const { token } = userInfo

        if (userUtils.isLoginValid()) {

            return this.request({
                url: '/mini/collection',
                method: 'DELETE',
                data: {
                    collection_ids,
                },
                header: {
                    Authorization: userUtils.getBearToken(token),
                }
            })
        }

        const empty = new Promise((resolve, reject) => {
            resolve({})
        })
        return empty
    }

    /**
     * 查询当前用户的收藏产品
     * @param page  当前页
     * @param page_size  每页总数
     */
    getCollection(page: number = 1, page_size: number = 10) {
        const userInfo = userUtils.getUserFromLocalStorage()
        const { token } = userInfo
        
        if (userUtils.isLoginValid()) {
            return this.request({
                url: '/mini/collection',
                data: {
                    page: page,
                    page_size,
                },
                header: {
                    Authorization: userUtils.getBearToken(token),
                }
            })
        }

        const empty = new Promise((resolve, reject) => {
            resolve({})
        })
        return empty
    }
}

export default CollectionService